/**
 * Created by TangZK on 2015/5/13.
 */
var Server = require('socket.io');
var chatModel = require('./chat_model.njs').chatModel;
var io = Server.listen(8090);
var easyChat = io.of('/easy-chat');

var userList = {}; // 用户列表，数据量大时，需换策略

easyChat.on('connection', function (socket) {

	socket.on('message', function (jsonStr) {
		var jo = JSON.parse(jsonStr);
		if(jo && jo.to) {
			var toUID = jo.to;
			var toUser = 'uid'+toUID;
			var fromUserInfo = jo.from;
			var data = {};
			var uID = fromUserInfo.user_id;
			data.uid = uID;
			data.to_uid = parseInt(toUID);

			if(jo.message.length > 0 && jo.message.length <= 256) {
				data.message = jo.message;
				var nowStamp = parseInt(Date.now() / 1000);
				data.send_time = nowStamp;
				chatModel.record(data, function(result) {
					socket.to(toUser).emit('message', JSON.stringify(jo));
				});
				var obj = {uid: uID, to_uid: toUID, send_time: nowStamp};
				socket.emit('msg_send_time', JSON.stringify(obj));
			} else {

			}
		}
		//socket.broadcast.emit('message', data);
	});

	socket.on('pull_msg_list', function(jsonStr) {
		var jo = JSON.parse(jsonStr);
		var uID = jo.uid, //当前登录用户的ID
			toUID = jo.to_uid; //发消息用户的ID
		var whereArr = [toUID, uID];
		chatModel.get_chat_list(whereArr, function(result, flag) {
			var dao = {};
			dao.uid = uID;
			dao.to_uid = toUID;
			dao.result = result;
			dao.flag = flag;
			socket.emit('msg_list', JSON.stringify(dao));
		});
	});

	// 更新消息状态
	socket.on('update_msg_state', function(jsonStr) {
		var jo = JSON.parse(jsonStr);
		var uID = jo.uid, //当前登录用户的ID
			toUID = jo.to_uid; //发消息用户的ID
		var nowStamp = parseInt(Date.now() / 1000);
		var dataArr = [nowStamp, toUID, uID];
		chatModel.change_msg_state(dataArr);
	});

	// 摘取在线的用户列表
	socket.on('pull_online_list', function() {
		socket.emit('online_list', JSON.stringify(userList));
	});

	// 获取历史消息
	socket.on('get_history_msg', function(jsonStr) {
		var jo = JSON.parse(jsonStr);
		var uID = parseInt(jo.uid), //当前登录用户的ID
			chatUID = parseInt(jo.chat_uid),
			page = parseInt(jo.page),
			send_time = jo.send_time || 0; //发消息用户的ID
		var whereObj = {uid: uID, chat_uid: chatUID};
		if(send_time > 0) {
			whereObj.send_time = send_time;
		}
		chatModel.get_history_msg_list(whereObj, page, function(result) {
			var dao = {};
			dao.uid = uID;
			dao.chat_uid = chatUID;
			dao.result = result;
			dao.page = ++page;
			socket.emit('history_msg', JSON.stringify(dao));
		});
	});

	socket.on('join', function(uid) {
		if(uid) {
			socket.broadcast.emit('user_online', uid);
			var joinUID = 'uid'+uid;
			socket.join(joinUID);
			socket.uid = uid; // TODO HAVE BUG
			userList[uid] = '';
		}
	});

	socket.on('disconnect', function () {
		socket.broadcast.emit('user_offline', socket.uid);
		delete userList[socket.uid];
	});

});

console.log('easy-chat is ready!');